﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _020_XOR
{
    class Program
    {
        static int function(int x, int key)
        {
            return (x + key) % 256;
        }

        static void doCrypt(byte[] array, byte[] crypt, int key, int rounds)
        {
            for (int j = 0; j < rounds; j++)
            {
                for (int i = 0; i < array.Length / 2; i++)
                {
                    int l = array[i * 2];
                    int r = array[i * 2 + 1];

                    crypt[i * 2] = (byte)(function(l, key) ^ r);
                    crypt[i * 2 + 1] = (byte)l;
                }
                for (int i = 0; i < crypt.Length; i++) array[i] = crypt[i];
            }
        }
        static void doDecrypt(byte[] array, byte[] crypt, int key, int rounds)
        {
            for (int j = 0; j < rounds; j++)
            {
                for (int i = 0; i < crypt.Length / 2; i++)
                {
                    int l = crypt[i * 2];
                    int r = crypt[i * 2 + 1];

                    array[i * 2] = (byte)r;
                    array[i * 2 + 1] = (byte)(l ^ function(r, key));
                }
                for (int i = 0; i < array.Length; i++) crypt[i] = array[i];
            }
        }

        static void Main(string[] args)
        {
            byte[] array = new byte[8];
            byte[] crypt = new byte[array.Length];
            int key = 11;

            Console.WriteLine("Enter {0} bytes", array.Length);
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = Byte.Parse(Console.ReadLine());
            }

            // Шифруем
            doCrypt(array, crypt, key, 16);


            Console.Write("Crypted:");
            for (int i = 0; i < crypt.Length; i++) Console.Write("{0} ", crypt[i]); Console.WriteLine();


            // Дешифруем
            doDecrypt(array, crypt, key, 16);


            Console.Write("Decrypt:");
            for (int i = 0; i < array.Length; i++) Console.Write("{0} ", array[i]); Console.WriteLine();


            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}
